package apache.openejb.message.driven.bean.client;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class HelloWorldRemoateClient {

    public static void main(String[] args) throws UnknownHostException, JMSException, InterruptedException, NamingException {
        //System.setProperty("MyJmsConnectionFactory", "connectionfactory:org.apache.activemq.ActiveMQConnectionFactory:tcp://localhost:61616");
        
        //different vm in same machine
        //System.setProperty("Resource/javax.jms.ConnectionFactory", "connectionfactory:org.apache.activemq.ActiveMQConnectionFactory:tcp://localhost:61616");
        //different vm in different machine
        System.setProperty("Resource/javax.jms.ConnectionFactory", "connectionfactory:org.apache.activemq.ActiveMQConnectionFactory:tcp://192.168.1.252:61616");
                
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
        //different vm in same machine
        //props.put(Context.PROVIDER_URL, "http://127.0.0.1:8080/tomee/ejb");
        //different vm in different machine
        props.put(Context.PROVIDER_URL, "http://192.168.1.252:8080/tomee/ejb");

        Context ctx = new InitialContext(props);        
        System.out.println(ctx.getEnvironment());
        
        ConnectionFactory cf = (ConnectionFactory) ctx.lookup("MyJmsConnectionFactory"); 
        Connection connection = cf.createConnection();
        connection.start();
        
        Queue destination = (Queue) ctx.lookup("RequestQueue");
        System.out.println(destination.getQueueName());
        
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(destination);

        String hostname = InetAddress.getLocalHost().getHostName();
        String msg = "Hello world by jms at " + hostname;
        TextMessage message = session.createTextMessage(msg);   
        producer.send(message);
        System.out.println("done");
        

        Thread.sleep(1000);
        session.commit();
        session.close();
        connection.close();
    }
}
